<?php

namespace App\Service;

use App\Post;
use App\Service\Wechat\Send;
use EasyWeChat\Broadcast\Broadcast;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Material\Material;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Service\WeChat\Material as MaterialResource;

class WeChat extends Model
{
    //

    private $options = [
        'debug'  => false,
        'app_id' => 'wx0aac34300c5a1982',
        'secret' => '132d1797e84428db705eabc15b078765',
        'token'  => 'weixin',
        'log' => [
            'level' => 'debug',
            'file'  => '/tmp/easywechat.log', // XXX: 绝对路径！！！！
        ],
    ];

    private $application;
    private $material;
    private $broadcast;
    private $userService;

    public function __construct (array $attributes = [])
    {
        parent::__construct($attributes);
        $this->application = new Application($this->options);
        $this->material = $this->application->material;
        $this->broadcast = $this->application->broadcast;
        $this->userService = $this->application->user;

    }
    public function getInstance(){
        return $this->application;
    }
    public function getMaterial($type){
        return $this->material->lists($type)->toArray();
    }
    public function uploadArticle($id = []){
        $data = [];
        if($id == []){
            return false;
        }else{
            if(is_array($id)){
                foreach ($id as $k=>$v){
                    $post = Post::where('id',$v)->first()->toArray();

                    if(count($post)>0){
                        if($post['thumb']){
                            $thumb_id =  $this->uploadThumb('storage/'.$post['thumb'],$post['thumb']);
                        }else{
                            return false;
                        }
                        $content = $this->modifyArticle($post['content'],$post['id']);
                        $content = $content?$content:'点击阅读原文查看所有内容';
                        $data[] = [
                            'title' =>  $post['post_title'],
                            'thumb_media_id'    =>  $thumb_id,
                            'digest'    =>  $post['digest'],
                            'content'   =>  $content,
                            'show_cover_pic'    =>  1,
                            'content_source_url'    =>  route('wap.post-index',['id'=>$post['id']])
                        ];
                    }else{

                    }
                }


            }else{
                $id = explode(',',$id);
                foreach ($id as $k=>$v){
                    $post = Post::where('id',$v)->first()->toArray();

                    if(count($post)>0){
                        if($post['thumb']){
                            $thumb_id =  $this->uploadThumb('storage/'.$post['thumb'],$post['thumb']);
                        }else{
                            return false;
                        }
                        $content = $this->modifyArticle($post['content'],$post['id']);
                        $content = $content?$content:'点击阅读原文查看所有内容';
                        $data[] = [
                            'title' =>  $post['post_title'],
                            'thumb_media_id'    =>  $thumb_id,
                            'digest'    =>  $post['digest'],
                            'content'   =>  $content,
                            'show_cover_pic'    =>  0,
                            'content_source_url'    =>  route('wap.post-index',['id'=>$post['id']])
                        ];
                    }else{

                    }
                }
            }
            $res = $this->material->uploadArticle($data);
            $list = $this->userService->lists()->toArray();
            $users = $list['data']['openid'];
            $result = [];
            MaterialResource::upload(MaterialResource::NEWS,$res);
            foreach ($users as $v){
                $result[] = $this->broadcast->preview(Broadcast::MSG_TYPE_NEWS,$res->media_id,$v);
            }
            //$this->broadcast->sendNews($res->media_id);
            Send::sendLog([
                'media_id'=>$res->media_id,
                'type'  =>  MaterialResource::NEWS,
            ],$data);
            return $res->media_id;
        }
    }
    public function uploadThumb($path,$name){
        //获取图片素材
        //$name = base
        $imageList = MaterialResource::getAll(MaterialResource::IMAGE);
        $imageList = coverKey($imageList,'name');
        if(isset($imageList[$name])){
            return $imageList[$name]['media_id'];
        }
        $realPath = realpath($path);
        $res = $this->material->uploadThumb($realPath);
        $data = $res?$res->toArray():[];
        if($data){
            $data['name'] = $name;
        }
        MaterialResource::upload(MaterialResource::IMAGE,$data);
        return $res->media_id;
    }
    public function modifyArticle($content,$id){
        $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
        $s = preg_replace_callback($pattern,function($matches) use ($pattern){
            $path =  realpath(substr($matches[1],1));
            $res = $this->material->uploadArticleImage($path);
            $r = str_replace($matches[1],$res->url,$matches[0]);
            return $r;//'http://mmbiz.qpic.cn/mmbiz_png/3Ry7JV1aiaBb5YRs23fjpUxgw6pL1pbtGT6bcEasdbGCaQdRPVC5L7ftZXF2Uhkr8jiaRtK3icDK6DBfBK1m3doaw/0';
        },$content);
        Post::where('id',$id)->update(['wx_content'=>$s]);
        return $s;
    }
    public function clearRequest(){
        $access_token = $this->application->access_token;
        return post_request('https://api.weixin.qq.com/cgi-bin/clear_quota?access_token='.$access_token->getToken(),['appid'=>$access_token->getAppId()]);
    }
    public function AsyncImage($arr = []){
    }
    public function init(){
        $res = $this->material->lists('news')->toArray();
        $this->article($res);
    }
    public function addOne(){
        $res = $this->material->lists('news',0,1)->toArray();
        $this->article($res);
    }
    private function article($res){
        $datas = [];
        if(isset($res['item'])&&$res['item']){
            foreach ($res['item'] as $k=>$v){
                foreach ($v['content']['news_item'] as $kk=>$vv){
                    $data = [
                        'post_title'    =>  $vv['title'],
                        'category_id'   =>  23,
                        'source'    =>  '',
                        'digest'    =>  $vv['digest'],
                        'thumb' =>  $vv['thumb_url'],
                        'content'   =>  $vv['content'],
                        'tpl'   =>  '',
                        'status'    =>  Post::PUBLISHED,
                        'is_recommend'    =>  Post::RECOMMENDED,
                        'sort'  =>  50,
                        'area_id'   =>  0,
                        'created_at'    => date('Y-m-d H:i:s',$v['update_time']),
                        'updated_at'    =>  date('Y-m-d H:i:s',$v['update_time']),
                        'is_wechat' =>  1
                    ];
                    $datas[] = $data;
                }
            }
        }
        $p = new Post();
        $p->insert($datas);
    }
}
